package servlet;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.PrintWriter;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

/**
 * Servlet implementation class MyHttpServlet
 */
@WebServlet("/MyHttpServlet")
public class MyHttpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected PrintWriter printWriter = null;
	protected void addTag(String name, String value) {
		if (printWriter!=null)
			printWriter.write("<" + name + ">" + value + "</" + name + ">"); 
	}
	protected Document getDocument(HttpServletRequest request) {
		StringBuffer readXml = new StringBuffer();
		String line = null;
		Document xmlDoc = null;
		boolean isNull = true;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null) {
				readXml.append(line);
				isNull = false;
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}

		if (isNull == false) {
			String xml = readXml.toString();
			try {
				xmlDoc = DocumentBuilderFactory.newInstance()
						.newDocumentBuilder()
						.parse(new ByteArrayInputStream(xml.getBytes()));

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return xmlDoc;
	}
}
